import Layout from '../components/Layout';
import React, { useRef, useState } from 'react';
import styled from 'styled-components';
import { TagsSection } from './Money/TagsSection';
import { NoteSection } from './Money/NotesSection';
import { CategorySection } from './Money/CategorySection';
import { NumberPadSection } from './Money/NumberPadSection';
import { useRecords } from 'hooks/useRecords';



const MyLayout = styled(Layout)`
  display: flex;
  flex-direction: column;
`
const CategoryWrapper = styled.div`
  background: #c4c4c4;
`
type Category = '-' | '+';

const defaultFormData = {
  tagIds: [] as number[],
  note: '',
  category: '-' as Category,
  amount: 0
}

function Money() {
  const [selected, setSelected] = useState(defaultFormData);
  // addRecord添加本地持久数据
  const {addRecord} = useRecords();
  // ts声明类型中的一部分用Partial
  const onChange = (obj: Partial<typeof selected>)=> {
    setSelected({...selected, ...obj})
  }
  const  ChildRef: any =  useRef();
  const submit = () => {
    if (addRecord(selected)) {
      alert('保存成功');
      ChildRef.current.changeVal()
      setSelected(defaultFormData);
    }
  };
  
  return (
    <MyLayout scrollTop={9999}>
      <TagsSection value={selected.tagIds}
        onChange={(tagIds) => onChange({tagIds})}></TagsSection>
      <NoteSection value={selected.note}
        onChange={(note) => onChange({note})}></NoteSection>
      <CategoryWrapper>
        <CategorySection value={selected.category}
          onChange={(category) => onChange({category})}></CategorySection>
      </CategoryWrapper>
      <NumberPadSection onRef={ChildRef} value={selected.amount}
        onChange={(amount) => onChange({amount})}
        onOk={submit}
      ></NumberPadSection>
    </MyLayout>
  );
}

export default Money;
